package com.atguigu.order.serivce.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.atguigu.order.bean.Order;
import com.atguigu.order.feign.ProductFeignClient;
import com.atguigu.order.serivce.OrderService;
import com.atguigu.product.bean.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.List;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    DiscoveryClient discoveryClient;
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    LoadBalancerClient loadBalancerClient;
    @Autowired
    ProductFeignClient productFeignClient;

    @SentinelResource(value = "createOrder", blockHandler = "createOrderFallback")
    @Override
    public Order createOrder(Long productId, Long userId) {
//        Product product = getProductById(productId);
//        Product product = getProductByIdWithLoadBalancer(productId);
//        Product product = getProductByIdWithLoadBalancerAnno(productId);
        Product product = productFeignClient.getProductById(productId);
        Order order = new Order();
        order.setId(1L);
        order.setUserId(userId);
        order.setAddress("上海市闵行区");
        order.setNickName("zhangsan");
        BigDecimal totalAmount = product.getPrice().multiply(new BigDecimal(product.getNum()));
        order.setTotalAmount(totalAmount);
        order.setProductList(List.of(product));

        return order;
    }

    //兜底回调
    public Order createOrderFallback(Long productId, Long userId, BlockException e) {
        Order order = new Order();
        order.setId(0L);
        order.setUserId(userId);
        order.setAddress("未知地址:" + e.getClass());
        order.setNickName("未知用户");
        order.setTotalAmount(new BigDecimal(0));
        order.setProductList(List.of());
        return order;
    }


    //1.普通调用
    private Product getProductById(Long productId) {
        //获取远端注册的service-product服务的地址
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        ServiceInstance serviceInstance = instances.get(0);
        //远程url，调用ProductController#getProduct
        String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/product/" + productId;
        log.info("url:{}", url);
        //发送远端请求
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }

    //2.负载均衡的调用loadBalancerClient.choose
    private Product getProductByIdWithLoadBalancer(Long productId) {
        //获取远端注册的service-product服务的地址
//        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
//        ServiceInstance serviceInstance = instances.get(0);
        ServiceInstance serviceInstance = loadBalancerClient.choose("service-product");
        //远程url，调用ProductController#getProduct
        String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/product/" + productId;
        log.info("url:{}", url);
        //发送远端请求
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }

    //3.注解的方式实现负载均衡，域名传递服务名称
    private Product getProductByIdWithLoadBalancerAnno(Long productId) {
        //获取远端注册的service-product服务的地址
//        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
//        ServiceInstance serviceInstance = instances.get(0);
//        ServiceInstance serviceInstance = loadBalancerClient.choose("service-product");
        String serviceName = "service-product";
        //远程url，调用ProductController#getProduct
        String url = "http://" + serviceName + "/product/" + productId;
        log.info("url:{}", url);
        //发送远端请求
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }
}
